package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 优先从请求头中获取用户信息
        String userId = request.getHeader("user-info");
        
        // 如果请求头中没有，则尝试从请求参数中获取（用于测试等场景）
        if (StrUtil.isBlank(userId)) {
            userId = request.getParameter("userId");
        }
        
        if (StrUtil.isNotBlank(userId)) {
            try {
                UserContext.setUser(Long.valueOf(userId));
            } catch (NumberFormatException e) {
                // 忽略无效的用户ID
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}